package com.shy.test;

import java.sql.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author shihaiyanng
 * @date 2021/11/14 4:46 下午
 */
public class DBUtils {

    private static String CLASS_NAME;
    private static String URL;
    private static String USER;
    private static String PWD;

    static {
        try {
            Properties properties = new Properties();
            InputStream inputStream = DBUtils.class.getClassLoader().getResourceAsStream("db.properties");
            properties.load(inputStream);
            CLASS_NAME = properties.getProperty("DRIVER_CLASS");
            URL = properties.getProperty("DB_URL");
            USER = properties.getProperty("DB_USER");
            PWD = properties.getProperty("DB_PASSWORD");
            Class.forName(CLASS_NAME);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        try {
            //获取连接对象
            Connection connection = DriverManager.getConnection(URL, USER, PWD);
            return connection;

        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void closeAll(Connection con, PreparedStatement ps, ResultSet rs){
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null){
                ps.close();
            }
            if (con != null){
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
